package vn.orderonline.core.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vn.orderonline.core.commons.utils.StringUtils;
import vn.orderonline.core.dao.member.MemberDao;
import vn.orderonline.core.redis.model.RedisServiceHelper;

@Service
public class UserRedisService extends RedisService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserRedisService.class);
	
	@Autowired
	private MemberDao memberDao;
	
	public RedisMember getUser(String username) {
		LOGGER.info("*** getUser() ***");
		if (StringUtils.isNullOrEmpty(username)) {
			return null;
		}
		String userKey = RedisServiceHelper.formatKey(RedisServiceHelper.USERPREFIX, username);
		RedisMember redisMember = hget(userKey, RedisMember.class, RedisServiceHelper.INFO);
		if (redisMember == null) {
			redisMember = memberDao.getRedisMemberByUsername(username);
			if (redisMember != null) {
				hset(userKey, RedisServiceHelper.INFO, redisMember);
				String emailKey = RedisServiceHelper.formatKey(RedisServiceHelper.EMAILPREFIX, redisMember.getMemberEmail());
				set(emailKey, userKey);
			}
		}
		LOGGER.info("*** getUser() --> END ***");
		return redisMember;
	}
	
	public RedisMember getUserByEmail(String email) {
		LOGGER.info("*** getUserByEmail() ***");
		RedisMember redisMember = null;
		if (StringUtils.isNullOrEmpty(email)) {
			return null;
		}
		String emailKey = RedisServiceHelper.formatKey(RedisServiceHelper.EMAILPREFIX, email);
		String userKey = get(emailKey, String.class);
		if (!StringUtils.isNullOrEmpty(userKey)) {
			redisMember = hget(userKey, RedisMember.class, RedisServiceHelper.INFO);
		} else {
			redisMember = memberDao.getRedisMemberByEmail(email);
			if (redisMember != null) {
				userKey = RedisServiceHelper.formatKey(RedisServiceHelper.USERPREFIX, redisMember.getUsername());
				hset(userKey, RedisServiceHelper.INFO, redisMember);
				set(emailKey, userKey);
			}
		}
		LOGGER.info("*** getUserByEmail() ***");
		return redisMember;
	}
	
	public void removeUser(String username, String email) {
		String userKey = RedisServiceHelper.formatKey(RedisServiceHelper.USERPREFIX, username);
		String emailKey = RedisServiceHelper.formatKey(RedisServiceHelper.EMAILPREFIX, email);
		if (StringUtils.isNullOrEmpty(email)) {
			delete(userKey);
		} else {
			delete(userKey, emailKey);
		}
	}
}
